<template>
  <div>
                <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数" type="warning"> </el-alert>
      <!-- 选择商品分类 -->
      <el-form>
        <el-form-item label="请选择商品分类">
            <el-cascader clearable v-model="selectedCateKeys" :options="cateList"
              :props="{ expandTrigger: 'hover',
              value: 'cat_id', label: 'cat_name', children: 'children' }"
                @change="cateChange"></el-cascader>
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button @click="addParams" type="primary" size="small" :disabled="isDisabled">添加参数</el-button>
            <el-table :data="manyTableList" border  style="width: 100%">
              <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag @close="handleTagClosed(scope.row,id)" closable v-for="(item,id) in scope.row.attr_vals" :key="id">{{item}}</el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)" >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
              </el-table-column>
              <el-table-column  label="#" width="180" type="index"> </el-table-column>
              <el-table-column  prop="attr_name" label="参数名称"> </el-table-column>
              <el-table-column label="操作" width="180px">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary"  icon="el-icon-edit" @click="editParamsInfo(scope.row.attr_id)" ></el-button>
                  <el-button  size="mini"  type="danger"  icon="el-icon-delete" @click="deleteParamsInfo(scope.row.attr_id)" ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button @click="addParams" type="primary" size="small" :disabled="isDisabled">添加属性</el-button>
            <el-table :data="onlyTableList" border  style="width: 100%">
              <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag @close="handleTagClosed(scope.row,id)" closable v-for="(item,id) in scope.row.attr_vals" :key="id">{{item}}</el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)" >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
              </el-table-column>
              <el-table-column  label="#" width="180" type="index"> </el-table-column>
              <el-table-column  prop="attr_name" label="属性名称"> </el-table-column>
              <el-table-column label="操作" width="180px">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary"  icon="el-icon-edit" @click="editParamsInfo(scope.row.attr_id)" ></el-button>
                  <el-button  size="mini"  type="danger"  icon="el-icon-delete" @click="deleteParamsInfo(scope.row.attr_id)" ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
    </el-card>
            <!-- 添加动态参数和静态属性的对话框(复用) -->
    <el-dialog :title="'添加' + chooseText" :visible.sync="addParamsDialogVisible"
      width="50%" @close="closeAddInfoForm">
      <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="addParamsFormRef" label-width="80px">
        <el-form-item :label="chooseText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddParams">确 定</el-button>
      </span>
    </el-dialog>
            <!-- 修改动态参数和静态属性的对话框(复用) -->
    <el-dialog :title="'修改' + chooseText" :visible.sync="editParamsDialogVisible"
      width="50%" @close="closeEditInfoForm">
      <el-form :model="editParamsForm" :rules="editParamsFormRules" ref="editParamsFormRef" label-width="80px">
        <el-form-item :label="chooseText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 选中的分类
      selectedCateKeys: [],
      activeName: 'many',
      // 动态参数面板参数数据
      manyTableList: [],
      // 静态属性面板数据
      onlyTableList: [],
      // 添加参数或者属性对话框
      addParamsDialogVisible: false,
      // 添加参数表单
      addParamsForm: {
        attr_name: ''
      },
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 修改参数或者属性对话框
      editParamsDialogVisible: false,
      // 修改参数表单
      editParamsForm: {
        attr_name: ''
      },
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 级联选择器选中的三级商品分类
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      } else {
        return null
      }
    },
    // 控制添加参数按钮
    isDisabled () {
      if (this.selectedCateKeys.length === 3) {
        return false
      } else {
        return true
      }
    },
    // 判断是参数还是属性面板
    chooseText () {
      if (this.activeName === 'many') {
        return '参数'
      } else {
        return '属性'
      }
    }
  },
  methods: {
    // 获取商品分类列表
    async getCatesList () {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('获取商品分类数据失败')
      } else {
        this.cateList = res.data
      }
    },
    // tab标签切换
    handleTabClick () {
      this.getParamsList()
    },
    // 级联选择器一旦选择
    cateChange () {
      // 限定只能选中三级分类
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableList = []
        this.onlyTableList = []
      }
      this.getParamsList()
    },
    // 获取所有参数列表
    async getParamsList () {
      // console.log(this.activeName)
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status === 200) {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          // 控制文本框和按钮的显示和隐藏（为防止出现联动效果，为美一行的数据都添加这两个自己的属性）
          item.inputVisible = false
          item.inputValue = ''
        })
        if (this.activeName === 'many') {
          this.manyTableList = res.data
        } else {
          this.onlyTableList = res.data
        }
        // console.log(this.onlyTableList)
      }
    },
    // 点击添加动态参数按钮，弹出对话框
    addParams () {
      this.addParamsDialogVisible = true
    },
    // 提交添加参数对话框
    submitAddParams () {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,
            {
              attr_name: this.addParamsForm.attr_name,
              attr_sel: this.activeName
            })
          if (res.meta.status !== 201) {
            this.$message.error('添加失败')
          } else {
            this.$message.success('添加成功')
            this.addParamsDialogVisible = false
            this.getParamsList()
          }
        } else {
          return false
        }
      })
    },
    // 添加参数对话框关闭
    closeAddInfoForm () {
      this.$refs.addParamsFormRef.resetFields()
    },
    // 点击修改动态参数按钮，弹出对话框
    async editParamsInfo (id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
        params: { attr_sel: this.activeName }
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数信息失败')
      } else {
        this.editParamsForm = res.data
        this.editParamsDialogVisible = true
      }
    },
    // 提交修改参数对话框
    submitEditParams () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
            {
              attr_name: this.editParamsForm.attr_name,
              attr_sel: this.activeName
            })
          if (res.meta.status !== 200) {
            this.$message.error('修改失败')
          } else {
            this.$message.success('修改成功')
            this.editParamsDialogVisible = false
            this.getParamsList()
          }
        } else {
          return false
        }
      })
    },
    // 添加参数对话框关闭
    closeEditInfoForm () {
      this.$refs.editParamsFormRef.resetFields()
    },
    // 删除参数
    deleteParamsInfo (id) {
      this.$confirm(`此操作将永久删除该${this.activeName === 'many' ? '参数' : '属性'}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败')
        } else {
          this.$message.success(res.meta.msg)
          this.getParamsList()
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 点击tag标签的关闭
    handleTagClosed (row, id) {
      row.attr_vals.splice(id, 1)
      this.submitAddInputTag(row)
    },
    // 键盘抬起或者失去交点，就从输入框变成了按钮
    handleInputConfirm (row) {
      // console.log(row)
      // 输入内容之后
      // 要对输入内容进行判断，如果未输入或者输入空格=>重新置为按钮
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      } else {
        // 输入内容=>将输入的内容加入数组，重置为按钮
        row.attr_vals.push(row.inputValue)
        row.inputValue = ''
        row.inputVisible = false
        // 还需要将数据存入后台
        this.submitAddInputTag(row)
      }
    },
    async submitAddInputTag (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          // 之前使用split(' ')将字符串隔成了数组，这里要变回去
          attr_vals: row.attr_vals.join(' ')
        })
      if (res.meta.status !== 200) {
        this.$message.error('更新失败')
      } else {
        this.$message.success('更新成功')
      }
    },
    // 点击按钮，按钮变成输入框
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获取焦点
      // 让页面上元素被渲染出来之后，再能够输入文本（该行数据渲染出来，才可以添加参数啊）
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  created () {
    this.getCatesList()
  }
}
</script>

<style scoped>
.el-breadcrumb{
    margin-bottom: 15px
}
.el-card{
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.5) !important
}
.el-alert{
  margin-bottom: 15px
}
.el-table{
  margin-top: 15px
}
.el-tag{
  margin: 10px
}
.input-new-tag{
  width: 70px
}
</style>
